#!/bin/bash

## Check Swagger-generated files under version control are up-to-date.
##
## Moves Swagger-generated files under version control to temporary
## directory, then attempts to re-generate them, checks that they are
## the same (apart from the code, that is allowed to differ in blank
## lines), finally restores the files under version control and
## deletes the temporary directory.
##
## As no multiple traps for the same signals can be set in `bash`,
## there is on failure a corner case that the (potentially non-empty)
## temporary directory is not deleted.

on_exit() {
    restore_vsnd_files
    rm -r "${TmpDir:?}"
}

restore_vsnd_files() {
    rm -rf "${SJ:?}"
    cp -p  "${TmpSJ:?}" "${SJ:?}"
}

set -e
set -x

SY="${1:?}" ## Swagger schema YAML file

## Make target for generating Swagger-related files under version
## control.  Assumptions:
## * Make file is in current working directory;
## * Make file is named so that make finds it without specifying
##   additional arguments.
MT="${2:?}"

## Generated Swagger-related files under version control.
SJ="${3:?}" ## Swagger schema JSON file - generated

## Create temporary directory.
TmpDir="$(mktemp -d)"

## Move old generated files under version control to temporary
## directory.  Ensure that on exit the files under version control are
## restored.
TmpSJ="${TmpDir:?}"/sj.backup
TmpPC="${TmpDir:?}"/pc.backup
cp -p  "${SJ:?}" "${TmpSJ:?}"
trap on_exit EXIT
rm    "${SJ:?}"

## Re-generate files.
make "${MT:?}"

## Check that re-generating JSON from YAML led to same generated JSON.
diff -u "${SJ:?}" "${TmpSJ:?}"
